package service.impl;

import models.Category;
import models.Content;
import models.ContentCategoryMap;
import play.db.jpa.JPA;
import service.ContentInterface;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

public class ContentImpl implements ContentInterface {
    @Override
    public List<Content> getContentListByPage(Integer contentType, String categoryType, Integer pageSize, Integer pageNum) {
        Category category = Category.find("category_key=?", categoryType).first();
        Integer categoryId;
        List<ContentCategoryMap> maps;
        StringBuffer ids = new StringBuffer();
        String idS = null;
        if(category!=null){
            categoryId = category.id;
            maps = ContentCategoryMap.find("category_id=?", categoryId).fetch();
            if(maps != null && !maps.isEmpty()){
                for(ContentCategoryMap map : maps){
                    ids.append(map.content_id).append(",");
                }
                idS = ids.substring(0, ids.length() - 1);
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append("select * from tos_content c where 1=1 ");
        if(idS!=null && !"".equals(idS)){
            sb.append(" and c.id in (").append(idS).append(") ");
        }
        if(contentType!=null && contentType > 0){
            sb.append(" and c.type = ").append(contentType);
        }
        Query query = JPA.em().createNativeQuery(sb.toString(), Content.class);
        query.setFirstResult((pageNum - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<Content> contentList = query.getResultList();
        for(Content content : contentList){
            List<ContentCategoryMap> mapList = ContentCategoryMap.find("content_id=?", content.id).fetch();
            List<Category> categoryList = new ArrayList<Category>();
            for(ContentCategoryMap map : mapList){
                Category category1 = Category.findById(map.category_id);
                categoryList.add(category1);
            }
            content.categoryList = categoryList;
        }
        return contentList;
    }
}
